package com.aistar.service.impl;

import com.aistar.mapper.ContestMapper;
import com.aistar.mapper.ProgramMapper;
import com.aistar.pojo.Contest;
import com.aistar.pojo.ContestExample;
import com.aistar.pojo.Program;
import com.aistar.service.ContestService;
import com.aistar.util.ServerResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContestServiceImpl implements ContestService {

    private  ContestMapper contestMapper;
    private ProgramMapper programMapper;

    @Autowired
    public ContestServiceImpl(ContestMapper contestMapper, ProgramMapper programMapper) {
        this.contestMapper = contestMapper;
        this.programMapper = programMapper;
    }

    @Override
    public ServerResponse getById(Integer id) {
        Contest contest = contestMapper.selectByPrimaryKey(id);
        if (contest!=null)
            return ServerResponse.getSuccess(contest);
        return ServerResponse.getFailed("竞赛信息异常");
    }


    //查找离现在的最近的一次的竞赛
    @Override
    public ServerResponse getRecentContest() {
        ContestExample example = new ContestExample();
        example.createCriteria().andStatusEqualTo(1).andContestEndTimeGreaterThan(new Date());
        example.setOrderByClause("contest_end_time ASC");
        List<Contest> list = contestMapper.selectByExample(example);
        if (list.size()>0)
            return ServerResponse.getSuccess(list.get(0));
        return ServerResponse.getFailed();
    }

    //过去的竞赛
    @Override
    public ServerResponse getPastContestByPage(Integer pageNum) {
        Page<Contest> contests = PageHelper.startPage(pageNum,7);
        ContestExample example = new ContestExample();
        example.createCriteria().andStatusEqualTo(1).andContestEndTimeLessThan(new Date());
        example.setOrderByClause("contest_end_time DESC");
        List<Contest> contestList = contestMapper.selectByExample(example);
        if (contestList != null && contestList.size()>0)
            return ServerResponse.getSuccess(contests.toPageInfo());
        return ServerResponse.getFailed();
    }

    @Override
    public ServerResponse modify(Contest contest) {
        int rows = contestMapper.updateByPrimaryKeySelective(contest);
        if (rows > 0)
            return ServerResponse.modifySuccess();
        return ServerResponse.modifyFailed();
    }

    //获取竞赛的题目信息
    @Override
    public ServerResponse getProgramById(Integer id) {
        Program program = programMapper.selectByPrimaryKey(id);
        if(program != null)
            return ServerResponse.getSuccess(program);
        return ServerResponse.getFailed();
    }
}
